package com.xbongbong.saas.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.distributor.dto.DistributorContactDeleteBatchDTO;
import com.xbongbong.distributor.dto.DistributorContactEditAttrUpdateDTO;
import com.xbongbong.distributor.dto.DistributorContactUpdateBatchDTO;
import com.xbongbong.distributor.dto.DistributorContactUpdateDTO;
import com.xbongbong.distributor.vo.DistributorContactDeleteBatchVO;
import com.xbongbong.distributor.vo.DistributorContactUpdateBatchVO;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasFormDataEsModel;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.ProSaveHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.pojo.InfoArrPojo;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasProcessTemplateModel;
import com.xbongbong.paas.pojo.AttrValuePojo;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.applist.pojo.AppListPojo;
import com.xbongbong.pro.applist.pojo.vo.ListAppVO;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.contactuser.pojo.dto.ContactUserDeleteBatchDTO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.BuinessDefaultErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.form.pojo.dto.ContactDataRepeatDTO;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainInLinkItemDTO;
import com.xbongbong.pro.message.constant.DistributorContactPushConstant;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.help.PushHelper;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.rabbitmq.producer.BaseProducer;
import com.xbongbong.pro.service.toolbox.elasticsearch.help.ProEsHelper;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ContactUserEntity;
import com.xbongbong.saas.domain.entity.ext.ContactEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.DistributorContactEnum;
import com.xbongbong.saas.enums.business.DistributorEnum;
import com.xbongbong.saas.help.LogHandleHelp;
import com.xbongbong.saas.help.SaasDataInitHelp;
import com.xbongbong.saas.help.SaasSaveHelp;
import com.xbongbong.saas.help.SaasUpdateHelp;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.model.ContactUserModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.service.ContactService;
import com.xbongbong.saas.service.ContactUserService;
import com.xbongbong.saas.service.DistributorContactService;
import com.xbongbong.saas.service.FundSetService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 *
 * @author mengna.deng
 * @date 2020/12/29 15:59
 * @version 1.0
 * @since V1.0
 */
@Service("distributorContactService")
public class DistributorContactServiceImpl implements DistributorContactService {

    private static final Logger LOG = LoggerFactory.getLogger(DistributorContactServiceImpl.class);

    @Resource
    private SaasUpdateHelp saasUpdateHelp;
    @Resource
    private SaasSaveHelp saasSaveHelp;
    @Resource
    private ContactService contactService;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private UserModel userModel;
    @Resource
    private ContactUserModel contactUserModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private ContactModel contactModel;
    @Resource
    private PushHelper pushHelper;
    @Resource
    private BaseProducer baseProducer;
    @Resource
    private FundSetService fundSetService;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;
    @Resource
    private PaasProcessTemplateModel paasProcessTemplateModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private ContactUserService contactUserService;
    @Resource
    private PaasFormDataEsModel paasFormDataEsModel;
    @Resource
    private ProEsHelper proEsHelper;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private LogHandleHelp logHandleHelp;

    @Override
    public void formatAddExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        //处理账期
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        fundSetService.formatPeriod(formatExplainDTO.getCorpid(), formatExplainDTO.getBusinessType(), formatExplainDTO.getFormId(), explainList);
    }

    @Override
    public void beforeSave(ValidateDataDTO validateDataDTO) throws XbbException {
        String corpid = validateDataDTO.getCorpid();
        JSONObject data = validateDataDTO.getData();
        SaasDataInitHelp.antDataSet(data, DistributorContactEnum.IS_MAIN.getAttr(), BasicConstant.ZERO);
        Map<String, FieldAttrEntity> explainMap = validateDataDTO.getExplainMap();
        Long id = validateDataDTO.getDataId();
        FieldAttrEntity fieldAttrEntity = new FieldAttrEntity();
        FieldAttrEntity distributorNameField = explainMap.getOrDefault(DistributorContactEnum.DISTRIBUTOR_NAME.getAttr(), fieldAttrEntity);
        // 格式化关联经销商
        saasSaveHelp.formatLinkBusiness4Save(data,DistributorContactEnum.DISTRIBUTOR_NAME.getAttr(), DistributorContactEnum.DISTRIBUTOR_NAME_LINK_TEXT.getAttr(), DistributorContactEnum.DISTRIBUTOR_NAME.getFieldType());
        // 是否来自关联新建
        SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo = validateDataDTO.getSaasNeedRedundantAttrPoJo();
        Integer isRelationItem = 0;
        if (!Objects.isNull(saasNeedRedundantAttrPojo)) {
            isRelationItem = saasNeedRedundantAttrPojo.getIsRelationItem();
        }
        Long distributorId = FastJsonHelper.getLongFromFormData(data, DistributorContactEnum.DISTRIBUTOR_NAME.getAttr());
        // 校验关联经销商是否存在
        if (!Objects.equals(isRelationItem,1)) {
            if (distributorId == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028.getCode(), ErrorMessageConstant.PLEASE_SELECT, Objects.toString(distributorNameField.getAttrName(), ""));
            }
            CustomerEntityExt customerEntityExt = customerModel.getByKey(distributorId, corpid);
            if (customerEntityExt == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028.getCode(), ErrorMessageConstant.ATTR_NOT_EXIST, Objects.toString(distributorNameField.getAttrName(), ""));
            }
            //bug:17151 客户只有1个联系人时，联系人未默认为客户的主联系人
            List<ContactUserEntity> contactUserList = contactUserModel.getListByCustomerId(corpid, distributorId);

            if (Objects.equals(data.get(ContactEnum.IS_MAIN.getAttr()),0)){
                if (CollectionUtils.isEmpty(contactUserList)) {
                    data.put(ContactEnum.IS_MAIN.getAttr(), BasicConstant.ONE);
                }
            }
        }
        // 生日
        saasSaveHelp.formatBirthday4Save(data, DistributorContactEnum.BIRTHDAY.getAttr(), DistributorContactEnum.BIRTHDAY_FLAG.getAttr(), DistributorContactEnum.BIRTHDAY_MMDD.getAttr());
        // 产品凤娇说取消单个客户判重和全局判重规则 2019/05/18
        // 获取联系人电话字段的电话判重规则
        FieldAttrEntity phoneField = explainMap.getOrDefault(DistributorContactEnum.PHONE.getAttr(), fieldAttrEntity);
        Integer phoneRepeatRule = phoneField.getNoRepeat();
        JSONArray phoneJsonArray = FastJsonHelper.getJsonArrFromFormData(data, DistributorContactEnum.PHONE.getAttr());

        List<String> contactPhoneList = new ArrayList<>();
        if (Objects.equals(isRelationItem,1) && saasNeedRedundantAttrPojo != null) {
            contactPhoneList = saasNeedRedundantAttrPojo.getContactPhoneList();
        }
        if (Objects.nonNull(phoneJsonArray)) {
            ContactDataRepeatDTO contactDataRepeatDTO = new ContactDataRepeatDTO(){{
                BeanUtil.copyProperties(validateDataDTO, this);
                setAttr(DistributorContactEnum.PHONE.getAttr());
                setSubAttr(StringConstant.PHONE_TEL_ATTR);
                setContactId(id);
                setCustomerId(distributorId);
                setPhoneRepeatRule(phoneRepeatRule);
            }};
            for (Object object : phoneJsonArray) {
                contactDataRepeatDTO.setContactPhoneList(contactPhoneList);
                JSONObject phoneJsonObject = (JSONObject) object;
                String tel = phoneJsonObject.getString(StringConstant.PHONE_TEL_ATTR);
                contactDataRepeatDTO.setTel(tel);
                boolean flag = contactService.contactRepeat(contactDataRepeatDTO);
                contactPhoneList.add(tel);
                if (flag) {
                    String msg = String.format(I18nMessageUtil.getMessage(ErrorMessageConstant.PHONE_NUMBER_ALREADY_EXIST), Objects.toString(phoneField.getAttrName(), ""), tel);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100034, msg);
                }
            }
        }
        validateDataDTO.setData(data);
    }

    @Override
    public void afterSave(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        PaasFormDataEntity newPaasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
        JSONObject newData = saasFormSaveDTO.getNewData();
        JSONObject oldData = saasFormSaveDTO.getOldData();
        Long distributorContactId = newPaasFormDataEntity.getId();
        String corpid = newPaasFormDataEntity.getCorpid();
        Boolean isNew = saasFormSaveDTO.getIsNew();
        Long newDistributorId = FastJsonHelper.getLongFromFormData(newData, DistributorContactEnum.DISTRIBUTOR_NAME.getAttr());
        Long oldDistributorId = FastJsonHelper.getLongFromFormData(oldData, DistributorContactEnum.DISTRIBUTOR_NAME.getAttr());
        if (!isNew) {
            if (!Objects.equals(newDistributorId, oldDistributorId)) {
                // 关联客户改变，删除原联系人协同团队
                contactUserModel.deleteBatchByCustomerAndContact(oldDistributorId, distributorContactId, corpid);
                // 建立联系人协同团队
                contactService.userRelateCustomerContact(newDistributorId, distributorContactId, corpid);
                // fix:21466 【成功部】联系人更换关联客户后主联系人显示异常
                if (Objects.equals(newData.get(DistributorContactEnum.IS_MAIN.getAttr()), 1)) {
                    BoolQueryBuilder boolQueryBuilder = boolQuery();
                    boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
                    boolQueryBuilder.filter(termQuery(DistributorContactEnum.getAttrConnectData(DistributorContactEnum.IS_MAIN), 1));
                    boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
                    boolQueryBuilder.mustNot((termQuery(StringConstant.SAAS_LINK_BUSINESS_ID, distributorContactId)));
                    boolQueryBuilder.filter(termQuery(DistributorContactEnum.getEsAttr4Keyword(DistributorContactEnum.DISTRIBUTOR_NAME), newDistributorId));
                    boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_CONTACT.getType()));
                    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                    sourceBuilder.query(boolQueryBuilder);
                    SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CONTACT.getIndex());
                    searchRequest.source(sourceBuilder);
                    Long count = xbbElasticsearchRestTemplate.count(searchRequest, PaasFormDataEntityExt.class);
                    if (count !=null && count > 0L) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put(ContactEnum.IS_MAIN.getAttr(), 0);
                        UpdateDataEntity updateData = ExplainUtil.getUpdateData(distributorContactId, jsonObject, corpid);
                        contactModel.updateBatch(Collections.singletonList(updateData), corpid);
                    }
                }
            }
        } else {
            // 建立联系人协同团队
            contactService.userRelateCustomerContact(newDistributorId, distributorContactId, corpid);

            Runnable runnable = () -> {
                try {
                    if (!Objects.equals(saasFormSaveDTO.getIsImport(), 1)) {
                        // 新建联系人消息推送
                        String creatorId = newPaasFormDataEntity.getCreatorId();
                        UserEntity creatorUser = userModel.getByKey(creatorId, corpid);
                        PaasFormDataEntityExt customerEntity = customerModel.getByKey(newDistributorId, corpid);
                        String customerName = "";
                        if (Objects.nonNull(customerEntity)) {
                            customerName = customerEntity.getData().getString(CustomerManagementEnum.NAME.getAttr());
                        }
                        ContactEntityExt contactEntityExt = new ContactEntityExt();
                        BeanUtil.copyProperties(newPaasFormDataEntity, contactEntityExt);
                        String contactName = saasFormSaveDTO.getNewData().getString(ContactEnum.NAME.getAttr());
                        List<String> pushUserList = pushHelper.getUserIdListByPushSetRule(corpid, PushTypeEnum.DISTRIBUTOR_CONTACT_ADD_PUSH.getCode(), PushTypeEnum.DISTRIBUTOR_CONTACT_ADD_PUSH.getSubCode(), creatorUser, contactEntityExt);
                        PushRefTypePojo.Options options = new PushRefTypePojo.Options(newPaasFormDataEntity.getAppId(), newPaasFormDataEntity.getMenuId(), newPaasFormDataEntity.getFormId(), distributorContactId, Collections.singletonList(distributorContactId), SaasMarkEnum.SAAS.getCode(),saasFormSaveDTO.getBusinessType() ,saasFormSaveDTO.getBusinessType());
                        MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, pushUserList, Collections.singletonList(distributorContactId), 0, null, I18nMessageUtil.getMessage(DistributorContactPushConstant.DISTRIBUTOR_CONTACT_ADD_TITLE), String.format(I18nMessageUtil.getMessage(DistributorContactPushConstant.DISTRIBUTOR_CONTACT_ADD_CONTENT), creatorUser.getName(), customerName, contactName), null, options);
                        baseProducer.sendMessage(PushTypeEnum.DISTRIBUTOR_CONTACT_ADD_PUSH, messageRabbitMqDTO);

                    }
                }catch (Exception e){
                    LOG.error("经销商联系人创建消息推送", e);
                }

            };
            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
        }
    }

    @Override
    public void batchEditAttr(DistributorContactEditAttrUpdateDTO distributorContactEditAttrUpdateDTO) throws XbbException {
        try {
            List<Long> idIn = distributorContactEditAttrUpdateDTO.getDataIdList();
            Map<String, Object> param = BeanUtil.convertBean2Map(distributorContactEditAttrUpdateDTO, true);
            param.put("idIn", idIn);
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            List<ContactEntityExt> contactList = contactModel.findEntitys(param);
            if (Objects.isNull(contactList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            // 审批通过后是否允许编辑
            Map<Long, Boolean> editAfterFinishedMap = paasProcessTemplateModel.getEditAfterFinishedMap(distributorContactEditAttrUpdateDTO.getCorpid(), distributorContactEditAttrUpdateDTO.getAppId(), distributorContactEditAttrUpdateDTO.getMenuId(), distributorContactEditAttrUpdateDTO.getLoginUser());
            List<PaasFormDataEntityExt> dataList = new ArrayList<>();
            BeanUtil.copyPropertiesList(contactList,dataList,PaasFormDataEntityExt.class);
            // 审批后能否编辑
            paasProcessTemplateModel.checkEditAfterFinished(editAfterFinishedMap, dataList);

            List<DistributorContactUpdateDTO> distributorContactUpdateList = new ArrayList<>();
            idIn.forEach((item)->{
                DistributorContactUpdateDTO distributorContactUpdateDTO = new DistributorContactUpdateDTO();
                distributorContactUpdateDTO.setId(item);
                JSONObject data = ProSaveHelp.getBatchUpdateData(distributorContactEditAttrUpdateDTO.getFieldEditedList());
                distributorContactUpdateDTO.setData(data);
                distributorContactUpdateList.add(distributorContactUpdateDTO);
            });
            if (!distributorContactUpdateList.isEmpty()) {
                DistributorContactUpdateBatchDTO distributorContactUpdateBatchDTO = new DistributorContactUpdateBatchDTO();
                BeanUtil.copyProperties(distributorContactEditAttrUpdateDTO, distributorContactUpdateBatchDTO);
                distributorContactUpdateBatchDTO.setDistributorContactList(distributorContactUpdateList);
                updateBatch(distributorContactUpdateBatchDTO);
            }

            // 批量编辑日志
            List<String> updataItemList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<Long> dataIdList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (ContactEntityExt item : contactList) {
                dataIdList.add(item.getId());
                JSONObject data = item.getData();
                String serialNo = item.getSerialNo();
                String opObjectName = data.getString(ContactEnum.NAME.getAttr());
                StringBuilder sb = new StringBuilder();
                opObjectName = opObjectName == null ? serialNo : sb.append(serialNo).append("（").append(opObjectName).append("）").toString();
                updataItemList.add(opObjectName);
            }
            String updataItem = StringUtils.join(updataItemList, "，");
            String userId = distributorContactEditAttrUpdateDTO.getUserId();
            String corpid = distributorContactEditAttrUpdateDTO.getCorpid();
            String loginUserName = distributorContactEditAttrUpdateDTO.getLoginUserName();

            String changedLogItemsStr = logHandleHelp.getChangedLogItemsStr(distributorContactEditAttrUpdateDTO.getLogFieldEditedList());
            if(dataIdList.size() > 1 ){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_DATA_BATCH_ATTR), loginUserName, XbbRefTypeEnum.CONTACT.getName(),
                        changedLogItemsStr, dataIdList.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTitle(XbbRefTypeEnum.DISTRIBUTOR_CONTACT.getName());
                infoArrPojo.setContent(updataItem);
                infoArrPojoList.add(infoArrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, loginUserName, OperateModuleTypeEnum.DISTRIBUTOR_CONTACT, OperateTypeEnum.EDIT,
                        "", "", memo, distributorContactEditAttrUpdateDTO.getHttpHeader());
            } else if (Objects.equals(dataIdList.size(), 1)){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_DATA_ATTR), loginUserName, XbbRefTypeEnum.DISTRIBUTOR_CONTACT.getName(), updataItem,
                        changedLogItemsStr);
                mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.DISTRIBUTOR_CONTACT, OperateTypeEnum.EDIT,
                        dataIdList.get(0).toString(), updataItem, memo, distributorContactEditAttrUpdateDTO.getHttpHeader());
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("distributorContactServiceImpl.batchEditAttr 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    @Override
    public DistributorContactUpdateBatchVO updateBatch(DistributorContactUpdateBatchDTO distributorContactUpdateBatchDTO) throws XbbException {
        DistributorContactUpdateBatchVO contactUpdateBatchVO = new DistributorContactUpdateBatchVO();
        try {
            String corpid = distributorContactUpdateBatchDTO.getCorpid();
            List<UpdateDataEntity> updateList = new ArrayList<>();
            List<DistributorContactUpdateDTO> contactUpdateList = distributorContactUpdateBatchDTO.getDistributorContactList();
            if (Objects.nonNull(contactUpdateList) && !contactUpdateList.isEmpty()) {
                contactUpdateList.forEach((item)->{
                    updateList.add(ExplainUtil.getUpdateData(item.getId(), item.getData(), corpid));
                });
            }
            contactModel.updateBatch(updateList, corpid);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            throw e;
        }
        return contactUpdateBatchVO;
    }

    @Override
    public DistributorContactDeleteBatchVO deleteBatch(DistributorContactDeleteBatchDTO distributorContactDeleteBatchDTO) throws XbbException {
        DistributorContactDeleteBatchVO distribuorContactDeleteBatchVO = new DistributorContactDeleteBatchVO();
        String corpid = distributorContactDeleteBatchDTO.getCorpid();
        try {
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(RedundantTemplateTypeEnum.CONTACT.getCode(), corpid);
            if (Objects.isNull(paasFormExplainEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            String explains = paasFormExplainEntity.getExplains();
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explains, null);
            // 查询所选客户列表
            List<Long> idIn = distributorContactDeleteBatchDTO.getDataIdList();
            Map<String, Object> param = BeanUtil.convertBean2Map(distributorContactDeleteBatchDTO, true);
            param.put("idIn", distributorContactDeleteBatchDTO.getDataIdList());
            List<ContactEntityExt> contactList = contactModel.findEntitys(param);
            if (Objects.isNull(contactList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            //查询名称
            List<String> contactName= new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for(ContactEntityExt entityExt : contactList){
                JSONObject data = entityExt.getData();
                String name = FastJsonHelper.getStringOrDefaultFromFormData(data, DistributorContactEnum.NAME.getAttr(), "");
                contactName.add(name);
            }
            // TODO 列表循环校验删除权限
            // 删除联系人
            if(!idIn.isEmpty()) {
                if(BasicConstant.ONE.equals(distributorContactDeleteBatchDTO.getSingleFlag())
                        && BasicConstant.ONE.equals(idIn.size())){
                    contactModel.deleteByKey(idIn.get(0),corpid);
                }else {
                    contactModel.deleteBatch(idIn, corpid);
                }
                distribuorContactDeleteBatchVO.setDeleteIds(idIn);
            }
            // 删除联系人关系
            ContactUserDeleteBatchDTO contactUserDeleteBatchDTO = new ContactUserDeleteBatchDTO();
            BeanUtil.copyProperties(distributorContactDeleteBatchDTO, contactUserDeleteBatchDTO);
            contactUserDeleteBatchDTO.setContactIdIn(idIn);
            contactUserService.deleteBatch(contactUserDeleteBatchDTO);

            Set<Long> customerIds = new HashSet<>();
            PaasFormDataEntityExt formData;
            for(ContactEntityExt entityExt : contactList){
                formData = saasUpdateHelp.getFormData(entityExt.getId(), distributorContactDeleteBatchDTO.getCorpid(),XbbRefTypeEnum.CONTACT.getCode() );
                if (formData ==null ){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                }
                if ( FlowStatusEnum.inApproval(formData.getFlowStatus()) ) {
                    throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200020);
                }
                JSONObject data = entityExt.getData();
                Long customerId = data.getLong(ContactEnum.CUSTOMER_NAME.getAttr());
                customerIds.add(customerId);
            }
            for(long customerId : customerIds){
                Map<String, String> sortMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                sortMap.put("field", ContactEnum.IS_MAIN.getAttr());
                sortMap.put("sort", SortOrder.DESC.toString());
                PaasFormDataEsListVO paasFormDataEsListVO = getEsListVoByLinkIdAndCondition(distributorContactDeleteBatchDTO, customerId, DistributorContactEnum.DISTRIBUTOR_NAME.getAttr(), XbbRefTypeEnum.CONTACT.getCode(), new ArrayList<>(), sortMap, explainMap);
                List<PaasFormDataEntityExt> paasFormDataESList = paasFormDataEsListVO.getPaasFormDataESList();
                // 判断删除联系人关联的客户是否只剩下一个联系人（bug:17151 客户只有1个联系人时，联系人默认为客户的主联系人）
                // List<ContactUserEntity> contactUserList = contactUserModel.getListByCustomerId(corpid, contactDeleteBatchDTO.getUserId(), customerId);
                if (paasFormDataESList.size() == 1) {
                    Long contactId = paasFormDataESList.get(0).getDataId();
                    ContactEntityExt contactEntityExt = contactModel.getByKey(contactId, corpid);
                    JSONObject contactEntityExtData = contactEntityExt.getData();
                    contactEntityExtData.put(ContactEnum.IS_MAIN.getAttr(), BasicConstant.ONE);
                    contactModel.update(contactEntityExt);
                }
            }
            OperateTypeEnum operateTypeEnum = OperateTypeEnum.DELETE;
            if (Objects.equals(1, distributorContactDeleteBatchDTO.getIsBusinessRule())) {
                operateTypeEnum = OperateTypeEnum.RULE_DELETE;
            }
            //生成删除日志(区分单个删除和批量删除)
            String userId = distributorContactDeleteBatchDTO.getUserId();
            String userName = distributorContactDeleteBatchDTO.getLoginUserName();
            String nameStr = StringUtils.join(contactName, "，");
            if(idIn.size() > 1){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_DELETE_FORM_DETAIL), userName, XbbRefTypeEnum.DISTRIBUTOR_CONTACT.getName(), idIn.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTitle(DistributorContactEnum.NAME.getAttrName());
                infoArrPojo.setContent(nameStr);
                infoArrPojoList.add(infoArrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, userName, OperateModuleTypeEnum.DISTRIBUTOR_CONTACT, operateTypeEnum,
                        "", "", memo, distributorContactDeleteBatchDTO.getHttpHeader());
            } else if (Objects.equals(idIn.size(), 1)){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_WORK), userName, XbbRefTypeEnum.DISTRIBUTOR_CONTACT.getName(), nameStr);
                mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.DISTRIBUTOR_CONTACT, operateTypeEnum,
                        idIn.get(0).toString(), nameStr, memo, distributorContactDeleteBatchDTO.getHttpHeader());
            }

        }catch (XbbException e){
            throw e;
        }catch (Exception e) {
            LOG.error("distributorContactModelImpl.deleteBatch 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return distribuorContactDeleteBatchVO;
    }

    /**
     * 根据关联id和条件获取数据
     *
     * @param distributorContactDeleteBatchDTO 入参
     * @param linkId              关联id
     * @return 数据
     * @throws XbbException 异常
     */
    private PaasFormDataEsListVO getEsListVoByLinkIdAndCondition(DistributorContactDeleteBatchDTO distributorContactDeleteBatchDTO, Long linkId, String attr, Integer businessType, List<ConditionsEntityExt> conditions, Map<String, String> sortMap, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        PaasFormDataEsListVO paasFormDataEsListVO;
        conditions.add(new ConditionsEntityExt(){{
            setAttr(attr);
            setSymbol(ConditionEnum.EQUAL.getSymbol());
            setValue(Collections.singletonList(linkId));
            setFieldType(FieldTypeEnum.TEXT.getType());
        }});
        FormDataListDTO formDataListDTO = new FormDataListDTO(){{
            BeanUtil.copyProperties(distributorContactDeleteBatchDTO, this);
            setAppId(null);
            setFormId(null);
            setDel(DelEnum.NORMAL.getDel());
            setConditions(conditions);
            setBusinessType(businessType);
            setSortMap(sortMap);
            setExplainMap(explainMap);
            setSearchSubForm(false);
        }};
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(formDataListDTO.getCorpid(), formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
        paasFormDataEsListVO = paasFormDataEsModel.list(formDataListDTO, indexTypeEnum);
        return paasFormDataEsListVO;
    }

    @Override
    public void updateRollback(List<Long> idIn, String corpid) throws XbbException {
        if (Objects.isNull(idIn) || idIn.isEmpty()) {
            return;
        }
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("idIn", idIn);
        param.put(StringConstant.CORPID, corpid);
        List<ContactEntityExt> contactList = contactModel.findEntitysWithoutSub(param);
        if (Objects.nonNull(contactList)) {
            for (ContactEntityExt item : contactList) {
                PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
                BeanUtil.copyProperties(item, paasFormDataEntity);
                proEsHelper.reductionEsInUpdate(paasFormDataEntity, item.getId(), corpid, IndexTypeEnum.IDX_SAAS_CONTACT);
            }
        }
    }

    @Override
    public ListAppVO formatContactAppList(FormDataListDTO formDataListDTO, List<PaasFormDataEntityExt> esEntities, Integer totalCount) throws XbbException {
        List<AppListPojo> appListPojos = new ArrayList<>();
        String corpid = formDataListDTO.getCorpid();
        Long formId = formDataListDTO.getFormId();
        for(PaasFormDataEntityExt entity : esEntities){
            JSONObject data = entity.getData();
            saasSaveHelp.formatLinkBusiness4Save(data, DistributorContactEnum.DISTRIBUTOR_NAME.getAttr(), DistributorContactEnum.DISTRIBUTOR_NAME_LINK_TEXT.getAttr(), DistributorContactEnum.DISTRIBUTOR_NAME.getFieldType());
        }

        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
        if (paasFormExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        for (PaasFormDataEntityExt entity : esEntities) {
            JSONObject data = entity.getData();
            Long id = entity.getDataId();
            JSONObject superScript = new JSONObject();
            JSONObject others = new JSONObject();

            List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
            appListPojos.add(new AppListPojo(id, titleList, summaryList, superScript, lablesList, others, entity.getAppId(), entity.getMenuId(), entity.getFormId()));
        }
        ListAppVO listAppVO = new ListAppVO();
        listAppVO.setList(appListPojos);
        listAppVO.setTotalCount(totalCount);
        return  listAppVO;
    }

    @Override
    public void formatLinkAddExplain(HandlerExplainInLinkItemDTO handlerExplainInLinkItemDTO) throws XbbException {
        JSONObject linkFormData = handlerExplainInLinkItemDTO.getLinkFormData();
        Long linkDataId = handlerExplainInLinkItemDTO.getLinkDataId();
        List<FieldAttrEntity> explainList = handlerExplainInLinkItemDTO.getExplainList();
        FieldAttrEntity linkCustomerField = new FieldAttrEntity();
        for(FieldAttrEntity fieldAttrEntity :explainList) {
            if (Objects.equals(fieldAttrEntity.getAttr(), DistributorContactEnum.DISTRIBUTOR_NAME.getAttr())) {
                linkCustomerField = fieldAttrEntity;
            }
        }
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(handlerExplainInLinkItemDTO.getLinkBusinessType());
        switch (redundantTemplateTypeEnum) {
            case CUSTOMER:
                String distributorName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, DistributorEnum.NAME.getAttr(), "");
                linkCustomerField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(linkDataId, distributorName));
                break;
            default:
                break;
        }
    }
}
